﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Windows.Media;
using PublicTemplateEditor.Helper;
using PublicTemplateEditor.Mold;
using System.Web;
using System.Windows.Controls;


namespace PublicTemplateEditor.DataAccess
{
    public class PageDA
    {
       
        #region 保存页面操作
        private static string insertPageSQL = "insert into m_page (Gid,PName,PBG,Pcfg,Month,thumbnail,ScreenShots,id)values ({0},'{1}','{2}','{3}','{4}',@thumbData,@screenData,'{5}') ;";
        private static string updatePageSQL = "update m_page set Gid={0},PName='{1}',PBG='{2}',pcfg='{3}',month='{4}',thumbnail = @thumbData ,ScreenShots=@screenData,modify=datetime('now','localtime') where id='{5}' ; ";
        private static string getPageByIDSQL = "select id,gid,pname,pbg,month,thumbnail,screenshots from m_page where id='{0}'";
        private static string getPageByNameSql = "select id,gid,pname,pbg,month,thumbnail,screenshots from m_page where pName = '{0}' ;";
        private static string getElementByPageSql = "select distinct id,ename,ecfg from m_element where pid='{0}'";
        private static string checkPageExit = "select count(1) from m_page where PName='{0}' ";
        private static string checkPageIDExit = "select count(1) from m_page where ID='{0}' ";
        private static string getPageListSql = "select id,pname,thumbnail from (select id,pname,thumbnail from m_page order by intime desc) limit {0} offset {1};";
        private static string getPageTotalSql = "select count(1) from m_page ";
        #endregion

        #region 页面sqlFormat

        /// <summary>
        /// 新增页面
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static string InsertPageSql(PageInfo page)
        {
            string sql = string.Empty;  
            sql = string.Format(insertPageSQL, page.GardenID, CommonHelper.Encode(page.PageName), page.BackgroundName,  "", page.Month, page.PageID);
            return sql;
        }

        /// <summary>
        /// 更新页面
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public static string UpdatePageSql(PageInfo page)
        {
            string sql = string.Empty;
            sql = string.Format(updatePageSQL, page.GardenID, CommonHelper.Encode(page.PageName), page.BackgroundName,  "", page.Month, page.PageID);
            return sql;
        }

        #endregion

        #region 读取页面和元素
        /// <summary>
        /// 依据页面id获取页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static PageInfo GetPageByID(string id)
        {
            PageInfo pageInfo = null;
            EditObjectDB eoDB = null;
            List<EditObjectDB> eoDBList = new List<EditObjectDB>();
            
            //获取页面
            string getPageSQL = string.Empty;
            getPageSQL = string.Format(getPageByIDSQL, id);
            object[] objList = CommonAccess.sqlite.GetRow(getPageSQL);
            if (objList == null)
                return null;
         
            pageInfo = new PageInfo() { PageID = objList[0].ToString(), 
                                        GardenID = CommonHelper.ConvertToInt(objList[1]),
                                        PageName =  CommonHelper.Decode(objList[2].ToString()),
                                        BackgroundName = objList[3].ToString(),
                                        Month = objList[4].ToString(),
                                        Thumbnail = CommonHelper.ConvertToByte(objList[5]),
                                        Screenshots = CommonHelper.ConvertToByte(objList[6])
                                        };
            //获取元素
            string getElementSQL = string.Format(getElementByPageSql, id);
            List<object[]> objArray = CommonAccess.sqlite.GetArray(getElementSQL);

            if (objArray == null)
                return null;
            
            foreach (object[] obj in objArray)
            {
                eoDB = new EditObjectDB()
                {
                    ID = obj[0].ToString(),
                    Name = obj[1].ToString().Trim(),
                    ConfigStr = obj[2].ToString()
                };
                    
                eoDBList.Add(eoDB);
            }

            pageInfo.EditObjectList = ElementDA.GetEditObject(eoDBList);

            return pageInfo;
        }

        /// <summary>
        /// 依据页面ID获取页面元素，不解析元素配置
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static List<EditObjectDB> GetElementByPage(string id)
        {
            #region 定义
            List<EditObjectDB> eoDBList = new List<EditObjectDB>();
            string getElementSQL = string.Format(getElementByPageSql, id);
            List<object[]> objArray = CommonAccess.sqlite.GetArray(getElementSQL);
            EditObjectDB eoDB = null;
            #endregion

            if (objArray == null)
                return null;
            
            foreach (object[] obj in objArray)
            {
                eoDB = new EditObjectDB()
                {
                    ID = obj[0].ToString(),
                    Name = obj[1].ToString(),
                    ConfigStr = obj[2].ToString()
                };

                eoDBList.Add(eoDB);
            }

            return eoDBList;
        }

        /// <summary>
        /// 检测名字是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool CheckPageName(string name)
        {
            string getElementSQL =  string.Format(checkPageExit,CommonHelper.Encode(name));
            object obj = CommonAccess.sqlite.GetScalar(getElementSQL);
            if (obj == null) return false;
            int count = CommonHelper.ConvertToInt(obj);

            if (count > 0)
                return true;
            else
                return false;
        }

        /// <summary>
        /// 检测页面是否存在 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool CheckPageID(string ID)
        {
            object obj =CommonAccess.sqlite.GetScalar(string.Format(checkPageIDExit, ID));
            if (obj == null) return false;
            if (CommonHelper.ConvertToInt(obj) > 0)
                return true;
            else
                return false;
        }

        #endregion

        #region 获取页面列表


        /// <summary>
        /// 页面列表
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        public static Dictionary<string, MaterialInfo> GetPageList(int limit, int offset)
        {

            Dictionary<string, MaterialInfo> brushDict = new Dictionary<string, MaterialInfo>();
            string sql = string.Format(getPageListSql, limit, offset);
            List<object[]> objList = CommonAccess.sqlite.GetArray(sql);
            if (objList == null)
                return null;

            MaterialInfo material;
            ImageSource source;
            foreach (object[] obj in objList)
            {
                material = new MaterialInfo();
                material.Guid = obj[0].ToString(); 
                material.Name = CommonHelper.Decode(obj[1].ToString());
                material.Type = EditTypes.PageThumbnail;
                byte[] byteArray = CommonHelper.ConvertToByte(obj[2]);
                if (byteArray != null)
                {
                    source = CommonHelper.GetImageSource(byteArray);
                    material.Source = source;
                }
                brushDict.Add(material.Guid.ToString(), material);
            }

            return brushDict;
        }

        /// <summary>
        /// 页面总数
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static int GetPagesTotal()
        {
            return   CommonAccess.sqlite.GetScalar(getPageTotalSql).ToInt();
        }

        #endregion

        #region 删除页面
        private static string deletePageSql = "delete from m_page where id='{0}' ;";
        private static string deleteElementByPageSql = "delete from m_element where pid='{0}' ;";
        private static string deleteMultiPageSql = "delete from m_page where id in ({0});delete from m_element where pid in ({0}) ;";

        /// <summary>
        /// 删除页面
        /// </summary>
        public static void DeletePage(string  pid)
        {
            if (CheckUsed(pid))
            {
                MessageBox.Show("该页面已经被使用，不能删除！");
                return;
            }
            string sql = string.Format(deletePageSql, pid) + string.Format(deleteElementByPageSql, pid);
            CommonAccess.sqlite.ExeSql(sql);
        }

        /// <summary>
        /// 删除页面，不检查是否存在
        /// </summary>
        public static void DeletePageWithNoCheck(string pid)
        {
            string sql = string.Format(deletePageSql, pid) + string.Format(deleteElementByPageSql, pid);
            CommonAccess.sqlite.ExeSql(sql);
        }

        /// <summary>
        /// 一次删除多个页面
        /// </summary>
        public static void DeleteMultiPage(string pid)
        {
            string sql = string.Format(deleteMultiPageSql, pid);
            CommonAccess.sqlite.ExeSql(sql);
        }

        #endregion

        #region 复制页面
        public static string CopyPage(string id)
        {
            #region 页面
            PageInfo pageInfo = null;
           
            //获取页面
            string getPageSQL = string.Format(getPageByIDSQL, id);
            object[] objList = CommonAccess.sqlite.GetRow(getPageSQL);
            if (objList == null)
                return string.Empty;

            pageInfo = new PageInfo()
            {
                PageID = CommonHelper.GetGuid(),
                GardenID = CommonHelper.ConvertToInt(objList[1]),
                PageName = "复件 "+ CommonHelper.Decode(objList[2].ToString()),
                BackgroundName = objList[3].ToString(),
                Month = objList[4].ToString(),
                Thumbnail = CommonHelper.ConvertToByte(objList[5]),
                Screenshots = CommonHelper.ConvertToByte(objList[6])
            };


            Dictionary<string, byte[]> pars = new Dictionary<string, byte[]>();
            pars.Add("thumbData", pageInfo.Thumbnail);
            pars.Add("screenData", pageInfo.Screenshots);
            #endregion

            #region 元素
            EditObjectDB eoDB = null;

            //获取元素
            string getElementSQL = string.Format(getElementByPageSql, id);
            List<object[]> objArray = CommonAccess.sqlite.GetArray(getElementSQL);
            if (objArray == null)
                return string.Empty;

            StringBuilder sb = new StringBuilder();
            foreach (object[] obj in objArray)
            {
                eoDB = new EditObjectDB()
                {
                    ID = CommonHelper.GetGuid(),
                    Name = obj[1].ToString(),
                    ConfigStr = obj[2].ToString(),
                    PID=pageInfo.PageID
                };
                sb.Append(ElementDA.InsertEditObjectSql(eoDB));
            }
            #endregion

            #region 存入数据库
            CommonAccess.sqlite.ExeSql(sb.ToString());
            CommonAccess.sqlite.ExeSql(InsertPageSql(pageInfo), pars);
            #endregion

            return pageInfo.PageID;
        }
        #endregion

        #region 检查页面是否已被使用
        /// <summary>
        /// 检查页面是否已被使用
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public static bool CheckUsed(string pid)
        {
            string sql = "select count(1) from m_mprelations where pid ='{0}';";
            object obj =  CommonAccess.sqlite.GetScalar(string.Format(sql,pid));
            if (obj.ToInt() > 0)
                return true;
            else
                return false;
        }
        #endregion

        #region  保存临时页面
        /// <summary>
        /// 用于系统崩溃时保存页面
        /// </summary>
        /// <param name="index"></param>
        public static void Save(IndexWindow index)
        {
            PageInfo page = (PageInfo)index.main.Tag;
            page.PageID = CommonHelper.GetGuid();
            if (page.EditObjectList.Count == 0) return;
            SqlLiteHelper sqlite = new SqlLiteHelper();
            string pName = "临时保存页面" + DateTime.Now.ToString();
           
            page.PageName = pName;
            page.Month = "-1";
            page.OperateType = OperateTypes.Add;
            page.IsOperate = true;

            #region 保存
            try
            {
                string sql = page.SavePageStr;
                if (!string.IsNullOrEmpty(sql))
                {
                    Dictionary<string, byte[]> pars = new Dictionary<string, byte[]>();
                    pars.Add("thumbData", page.Thumbnail);
                    pars.Add("screenData", page.Screenshots);

                    sqlite.ExeSqlOut(page.SavePageStr, pars);
                }

                foreach (EditObject eo in page.EditObjectList)
                {
                    eo.IsOperate = true;
                    eo.OperType = OperateTypes.Add;
                    eo.Guid = CommonHelper.GetGuid();
                }

                string str = page.SaveElementStr;
                if (!string.IsNullOrEmpty(str))
                {
                    sqlite.ExeSql(str);
                }
            }
            catch (Exception ex)
            {
                FileHelper.WriteError("页面保存失败", ex);
            }
            #endregion
        }
        #endregion
    }
}
